<template>
  <div id="editRoleQx">
    <div class="pageMain">
      <!-- <el-form :model="roleOperationParams" :rules="rules" ref="roleOperationParams" label-width="100px" class="roleOperationParams" :disabled="isEdit ? false : true">
        <div class="formHead">{{ $route.query.type == 'isAddJump' ? '角色添加' : '角色修改'}}</div>
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="roleOperationParams.roleName" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item label="备注信息：" prop="remarks">
            <el-input type="textarea" v-model="roleOperationParams.remarks" style="width: 444px;"></el-input>
          </el-form-item>
      </el-form> -->
      <div class="Jurisdiction">
        <div class="formHead">
          <div class="titleCount">
            <span class="title">普及版权限设置</span>
            <el-select v-model="smallType" @change="getTreeData" style="width: 120px; margin-left: 20px" placeholder="请选择版本">
              <el-option label="云会计迷你版" value="3"></el-option>
              <el-option label="云会计" value="7"></el-option>
              <el-option label="云会计增强包" value="0"></el-option>
              <el-option label="云会计plus" value="5"></el-option>
              <el-option label="云会计plus1" value="6"></el-option>
              <el-option label="小微ERP标准版" value="1"></el-option>
              <el-option label="小微ERP专业版" value="2"></el-option>
              <el-option label="个人兼职版" value="4"></el-option>
              <el-option label="银行" value="9"></el-option>
            </el-select>
            <span class="newly" @click="newly(0)">新增</span>
          </div>
          <div class="titleCount">
            <span class="title">高级版权限设置</span>
          </div>
        </div>
        <div class="treeContent">
          <!-- draggable -->
          <el-tree @node-drag-end="handleDrop" accordion expand-on-click-node :data="treeData" node-key="id" :props="defaultProps" :render-content="sectionrenderContent" @node-expand="nodeExpand" @node-collapse="nodeCollapse" :default-expanded-keys="expanded" v-loading="treeLoading"> </el-tree>
        </div>
        <div class="treeContent">
          <!-- draggable -->
          <el-tree @node-drag-end="handleDrop1" accordion expand-on-click-node :data="treeData1" node-key="id" :props="defaultProps" :render-content="sectionrenderContent1" @node-expand="nodeExpand1" @node-collapse="nodeCollapse1" :default-expanded-keys="expanded1" v-loading="treeLoading1"> </el-tree>
        </div>
      </div>
      <!-- <div class="Jurisdiction">
        <div class="formHead">
          <span class="title">高级版权限设置</span>
        </div>

      </div> -->
    </div>
    <!-- <div class="pageFooter">
      <el-button  size="medium" round @click="cancelSave">取 消</el-button>
      <el-button  size="medium" type="primary" round :loading="isConfirmLoading" style="margin-left: 30px;" @click="saveRoleChange">保 存</el-button>
    </div> -->
    <!-- 新增修改权限 -->
    <el-dialog :title="jurisdictionPopup.title" :visible.sync="jurisdictionPopup.isShow" width="380px" @closed="handleClose">
      <el-form :model="jurisdictionParams" :rules="rules" ref="depForm" @submit.native.prevent label-width="130px" style="padding: 40px 0">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model.trim="jurisdictionParams.name" ref="Permission_name" placeholder="请输入权限名称"></el-input>
        </el-form-item>
        <el-form-item label="默认开通" prop="isopen">
          <el-switch v-model="jurisdictionParams.isopen"></el-switch>
        </el-form-item>
        <el-form-item v-show="jurisdictionPopup.sqlType == 1" label="是否同步到企业号" prop="isSync">
          <el-switch v-model="isSync"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="jurisdictionPopup.isShow = false" round>取 消</el-button>
        <el-button size="medium" type="primary" @click="changeDep" round :loading="isConfirmLoading">保 存</el-button>
      </span>
    </el-dialog>
    <el-dialog title="系统提示" :visible.sync="dialogVisible" width="30%" :show-close="false" :close-on-click-modal="false" @closed="closedFun">
      <el-input v-model.trim="password" type="password" ref="Permission_name" placeholder="请输入密码"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "editRoleQx",
  data() {
    return {
      treeData: [],
      treeData1: [],
      treeLoading1: false,
      treeLoading: false,
      defaultProps: {
        children: "childrenList",
        label: "name",
      },
      isConfirmLoading: false,
      dialogVisible: false,
      jurisdictionPopup: {
        title: "",
        isShow: false,
      },
      jurisdictionParams: {
        // 权限对象
        name: "", // 权限名称
        isopen: false,
      },
      expanded: [],
      expanded1: [],
      smallType: "2",
      isSync: false,
      password: '',
      treeItem: '',
      rules: {
        name: [{ required: true, message: "请输入权限名称", trigger: "blur" }],
      },
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.common.userInfo,
    }),
  },
  methods: {
    confirm() {
      if(this.getTime() == this.password) this.dialogVisible = false;
      else this.$message({ message: "密码错误", type: "warning" });
    },
    closedFun() {
      if(this.password != this.getTime()) {
        this.$message({ message: "请填写密码", type: "warning" });
        this.dialogVisible = true;
      }
    },
    getTime() {
      var date = new Date();
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      var d = date.getDate();
      m = m < 10 ? '0' + m : m;
      d = d < 10 ? '0' + d : d;
      var h = date.getHours();  
      h = h < 10 ? '0' + h : h;  
      // var minute = date.getMinutes();  
      // minute = minute < 10 ? '0' + minute : minute;  
      // var second = date.getSeconds();  
      // second = second < 10 ? '0' + second : second;  
      let time = y + '-' + m + '-' + d + '-' + h;
      return time;
    },
    nodeExpand(node) {
      this.expanded.push(node.id);
    },
    nodeCollapse(node) {
      let index = this.expanded.indexOf(node.id);
      this.expanded.splice(index, 1);
    },
    nodeExpand1(node) {
      this.expanded1.push(node.id);
    },
    nodeCollapse1(node) {
      let index = this.expanded1.indexOf(node.id);
      this.expanded1.splice(index, 1);
    },
    handleClose() {
      this.jurisdictionParams = { name: "" };
    },
    newly(Type) {
      // 新增一级
      this.jurisdictionPopup = {
        title: Type == 0 ? "普及版权限新增一级" : "高级版权限新增一级",
        isShow: true,
        sqlType: 1,
        type: Type,
      };
      this.jurisdictionParams = {
        name: "",
        id: 0,
        parentid: 0,
        rootid: 0,
        islast: true,
        level: 1,
        code: "",
        sort: Type == 0 ? this.treeData.length + 1 : this.treeData1.length + 1,
        isopen: false,
        smallType: Type == 0 ? Number(this.smallType) : 2,
      };
      this.treeItem = { isNoCode: 0 };
      this.geFocus();
    },
    changeDep() {
      // 确认修改 | 新增
      this.$refs["depForm"].validate((valid) => {
        if (valid) {
          this.isConfirmLoading = true;
          this.modification(this.jurisdictionParams);
        } else {
          return false;
        }
      });
    },

    modification(jurisdictionParams) {
      let params = {
        ...jurisdictionParams,
      };
      if(this.treeItem.isNoCode == 1) params.roleid = this.userInfo.roleid;
      this.$api.publicApi[this.treeItem.isNoCode == 0 ? 'TemplateAuthorityEdit' : 'EditAuthority'](this.jurisdictionPopup, params).then((res) => {
        this.editCode(res);
      })
        .catch(() => {
          this.isConfirmLoading = false;
        });
    },
    editCode(res) {
      this.isConfirmLoading = false;
      this.jurisdictionPopup.isShow = false;
      if (res.data.status == 200) {
        this.jurisdictionPopup.type == 0 ? this.getTreeData() : this.getTreeData1();
        if (this.jurisdictionPopup.sqlType == 1 && this.isSync) {
          // 新增时是否同步到企业号
          this.isSync = false;
          this.setSync(res.data.data, this.jurisdictionPopup.type);
        }
        this.$message({ message: "编辑成功", type: "success" });
      }
    },
    setSync(item, Type) {
      //同步其他企业号
      let params = {
        ...item,
      };
      this.$api.publicApi.SyncAuthority({ type: Type }, params).then((res) => {});
    },

    handleDrop(draggingNode, dropNode, dropType) {
      // 拖拽成功完成时触发的事件
      this.setHandleDrop(draggingNode, dropNode, dropType, 0);
    },

    handleDrop1(draggingNode, dropNode, dropType) {
      // 拖拽成功完成时触发的事件
      this.setHandleDrop(draggingNode, dropNode, dropType, 1);
    },

    setHandleDrop(draggingNode, dropNode, dropType, type) {
      let drop = dropNode.data;
      let params = {
        ...draggingNode.data,
      };
      if (dropType == "before") {
        // 前
        params.parentid = drop.parentid;
        params.rootid = drop.rootid;
        params.level = drop.level;
        params.sort = Number(drop.sort) - 1;
        if (params.sort <= 0) params.sort = 1;
      } else if (dropType == "after") {
        // 后
        params.parentid = drop.parentid;
        params.rootid = drop.rootid;
        params.level = drop.level;
        params.sort = Number(drop.sort) + 1;
      } else if (dropType == "inner") {
        // 内部
        params.parentid = drop.id;
        params.rootid = drop.level == 1 ? drop.id : drop.rootid;
        params.level = Number(drop.level) + 1;
        params.sort = drop.childrenList.length;
      }
      this.modification(params, { sqlType: 2, type });
    },

    setis_show(data) {
      data.is_show = true;
    },
    setis_show1(data) {
      data.is_show = false;
    },

    sectionrenderContent(h, { data }) {
      // 自定义tree节点
      return (
        <span class="sectiontreenode" on-mouseenter={() => this.setis_show(data)} on-mouseleave={() => this.setis_show1(data)}>
          <span class="sectionItem">
            <span>{data.name}</span>
          </span>
          <div class="operation sectionItem" v-show={data.is_show}>
            <i class="iconfont" on-click={() => this.treeOperation(data, "add", 0)}>
              &#xe632;
            </i>
            <i class="iconfont" on-click={() => this.treeOperation(data, "edit", 0)}>
              &#xe631;
            </i>
            <i class="iconfont" on-click={() => this.treeOperation(data, "del", 0)}>
              &#xe672;
            </i>
          </div>
        </span>
      );
    },
    sectionrenderContent1(h, { data }) {
      // 自定义tree节点
      return (
        <span class="sectiontreenode" on-mouseenter={() => this.setis_show(data)} on-mouseleave={() => this.setis_show1(data)}>
          <span class="sectionItem">
            <span>{data.name}</span>
          </span>
          <div class="operation sectionItem" v-show={data.is_show}>
            <i class="iconfont" on-click={() => this.treeOperation(data, "add", 1)}>
              &#xe632;
            </i>
            <i class="iconfont" on-click={() => this.treeOperation(data, "edit", 1)}>
              &#xe631;
            </i>
            <i class="iconfont" on-click={() => this.treeOperation(data, "del", 1)}>
              &#xe672;
            </i>
          </div>
        </span>
      );
    },

    geFocus() {
      this.$nextTick(() => {
        this.$refs.Permission_name.$el.querySelector("input").focus();
      });
    },

    treeOperation(item, type, Type) {
      this.treeItem = item;
      // tree 操作
      event.stopPropagation();
      switch (type) {
        case "add":
          this.jurisdictionPopup = {
            title: Type == 0 ? "普及版权限新增" : "高级版权限新增",
            isShow: true,
            sqlType: 1,
            type: Type,
          };
          this.jurisdictionParams = {
            name: "",
            id: 0,
            parentid: item.id,
            rootid: item.level == 1 ? item.id : item.rootid,
            islast: true,
            level: Number(item.level) + 1,
            code: "",
            sort: item.childrenList ? Number(item.childrenList?.length) + 1 : 0,
            isopen: false,
            smallType: Type == 0 ? Number(this.smallType) : 2,
          };
          this.geFocus();
          break;
        case "edit":
          this.jurisdictionPopup = {
            title: Type == 0 ? "普及版权限修改" : "高级版权限修改",
            isShow: true,
            sqlType: 2,
            type: Type,
          };
          this.jurisdictionParams = {
            name: item.name,
            id: item.id,
            parentid: item.parentid,
            rootid: item.rootid,
            islast: item.islast,
            level: item.level,
            code: item.code,
            sort: item.sort,
            isopen: item.isopen,
            smallType: Type == 0 ? Number(this.smallType) : 2,
          };
          this.geFocus();
          break;
        case "del":
          this.$confirm("确认删除此权限吗？,请谨慎删除", "删除权限", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              let params = {
                name: item.name,
                id: item.id,
                parentid: item.parentid,
                rootid: item.rootid,
                islast: item.islast,
                level: item.level,
                code: item.code,
                sort: item.sort,
                isopen: item.isopen,
                smallType: Type == 0 ? Number(this.smallType) : 2,
              };
              if(item.isNoCode == 1) params.roleid = this.userInfo.roleid;
              this.$api.publicApi[item.isNoCode == 0 ? 'TemplateAuthorityEdit' : 'EditAuthority']({ sqlType: 3, type: Type }, params).then((res) => {
                if (res.data.status == 200) {
                  Type == 0 ? this.getTreeData() : this.getTreeData1();
                  this.$message({ message: "删除成功", type: "success" });
                }
              });
            })
            .catch(() => {});
          break;
        default:
          break;
      }
    },
    setTreeData(data) {
      data.map((item) => {
        item.is_show = false;
        if (item.childrenList && item.childrenList.length != 0) {
          this.setTreeData(item.childrenList);
        }
      });
    },
    getTreeData() {
      // 普及版
      this.treeLoading = true;
      this.$api.publicApi.GetTemplateAuthorityTree({ type: 0, smallType: this.smallType }).then((res) => {
        if (res.data.status == 200) {
          let resData = res.data.data;
          this.setTreeData(resData);
          this.treeData = resData;
        } else {
          this.treeData = [];
        }
        this.treeLoading = false;
      });
    },
    getTreeData1() {
      // 高级版
      this.treeLoading1 = true;
      this.$api.publicApi.GetTemplateAuthorityTree({ type: 1, smallType: 2 }).then((res) => {
        if (res.data.status == 200) {
          let resData = res.data.data;
          this.setTreeData(resData);
          this.treeData1 = resData;
        } else {
          this.treeData1 = [];
        }
        this.treeLoading1 = false;
      });
    },
    keyDown(e) {
      //回车保存
      if (e.keyCode === 13 && this.jurisdictionPopup.isShow) {
        this.changeDep();
      }
    },
  },
  created() {
    // 绑定事件
    window.addEventListener("keydown", this.keyDown);
  },
  destroyed() {
    // 登录成功后销毁事件
    window.removeEventListener("keydown", this.keyDown, false);
  },
  mounted() {
    this.getTreeData();
    this.getTreeData1();
    this.dialogVisible = true;
  },
};
</script>

<style lang="less">
#editRoleQx {
  overflow: auto;
  padding: 0;
  height: 100%;
  .pageMain {
    padding: 15px 15px 0 15px;
    margin-top: 0;
    // height: calc(100% - 60px);
    height: 100%;
    .Jurisdiction {
      height: calc(100% - 10px);
    }
  }
  .el-form {
    .el-input {
      width: 200px;
    }
  }
  .pageFooter {
    float: left;
    height: 60px;
    line-height: 60px;
    border-top: 1px solid #edecf6;
    width: 100%;
    text-align: center;
    background: #fff;
    z-index: 2;
  }
  .treeContent {
    width: 50%;
    display: inline-block;
    float: left;
    font-size: 14px;
    height: calc(100% - 66px);
    overflow: auto;
    .el-tree {
      height: 100%;
    }
  }
  .formHead {
    .titleCount {
      width: 50%;
      display: inline-block;
    }
    .title {
      display: inline-block;
    }
    .newly {
      cursor: pointer;
      margin-left: 30px;
      font-size: 13px;
      color: #39a4ed;
      &:hover {
        color: #1b97eb;
        text-decoration: underline;
      }
    }
  }
  .sectiontreenode {
    display: block;
    width: 100%;
    font-size: 13px;
    height: 40px;
    line-height: 40px;
    .sectionItem {
      display: inline-block;
      width: 50%;
    }
    .operation {
      width: 19%;
      text-align: center;
      i {
        font-size: 15px;
        margin-left: 10px;
        color: #39a4ed;
      }
    }
  }
}
</style>
